//! 基于Crossbeam的高性能队列实现
//! 
//! 提供线程安全的MPMC队列抽象和Crossbeam实现

use crossbeam::channel::{unbounded, bounded, Receiver, Sender};
use std::time::Duration;

/// 多生产者多消费者队列trait
/// 
/// 定义了线程安全队列的基本操作接口
pub trait MPMCQueue<T>: Send + Sync {
    /// 入队操作
    fn enqueue(&self, item: T) -> Result<(), T>;
    
    /// 尝试入队（非阻塞）
    fn try_enqueue(&self, item: T) -> Result<(), T>;
    
    /// 出队操作
    fn dequeue(&self) -> Option<T>;
    
    /// 尝试出队（非阻塞）
    fn try_dequeue(&self) -> Option<T>;
    
    /// 带超时的出队操作
    fn dequeue_timeout(&self, timeout: Duration) -> Option<T>;
    
    /// 获取队列长度（近似值）
    fn len(&self) -> usize;
    
    /// 检查队列是否为空
    fn is_empty(&self) -> bool;
    
    /// 获取队列容量信息
    fn capacity_info(&self) -> (usize, bool) {
        (self.len(), self.is_empty())
    }
}

/// 基于Crossbeam的无界MPMC队列
/// 
/// 使用crossbeam::channel::unbounded实现的高性能无锁队列
pub struct CrossbeamUnboundedQueue<T> {
    sender: Sender<T>,
    receiver: Receiver<T>,
}

impl<T> CrossbeamUnboundedQueue<T> {
    /// 创建新的无界队列
    pub fn new() -> Self {
        let (sender, receiver) = unbounded();
        Self { sender, receiver }
    }
    
    /// 获取发送器克隆
    pub fn sender(&self) -> Sender<T> {
        self.sender.clone()
    }
    
    /// 获取接收器克隆
    pub fn receiver(&self) -> Receiver<T> {
        self.receiver.clone()
    }
}

impl<T> Default for CrossbeamUnboundedQueue<T> {
    fn default() -> Self {
        Self::new()
    }
}

impl<T: Send> MPMCQueue<T> for CrossbeamUnboundedQueue<T> {
    fn enqueue(&self, item: T) -> Result<(), T> {
        self.sender.send(item).map_err(|e| e.0)
    }
    
    fn try_enqueue(&self, item: T) -> Result<(), T> {
        self.sender.try_send(item).map_err(|e| match e {
            crossbeam::channel::TrySendError::Full(item) => item,
            crossbeam::channel::TrySendError::Disconnected(item) => item,
        })
    }
    
    fn dequeue(&self) -> Option<T> {
        self.receiver.recv().ok()
    }
    
    fn try_dequeue(&self) -> Option<T> {
        self.receiver.try_recv().ok()
    }
    
    fn dequeue_timeout(&self, timeout: Duration) -> Option<T> {
        self.receiver.recv_timeout(timeout).ok()
    }
    
    fn len(&self) -> usize {
        self.receiver.len()
    }
    
    fn is_empty(&self) -> bool {
        self.receiver.is_empty()
    }
}

/// 基于Crossbeam的有界MPMC队列
/// 
/// 使用crossbeam::channel::bounded实现的有界队列
pub struct CrossbeamBoundedQueue<T> {
    sender: Sender<T>,
    receiver: Receiver<T>,
    capacity: usize,
}

impl<T> CrossbeamBoundedQueue<T> {
    /// 创建指定容量的有界队列
    pub fn with_capacity(capacity: usize) -> Self {
        let (sender, receiver) = bounded(capacity);
        Self { sender, receiver, capacity }
    }
    
    /// 获取队列容量
    pub fn capacity(&self) -> usize {
        self.capacity
    }
    
    /// 检查队列是否已满
    pub fn is_full(&self) -> bool {
        self.receiver.len() >= self.capacity
    }
    
    /// 获取发送器克隆
    pub fn sender(&self) -> Sender<T> {
        self.sender.clone()
    }
    
    /// 获取接收器克隆
    pub fn receiver(&self) -> Receiver<T> {
        self.receiver.clone()
    }
}

impl<T: Send> MPMCQueue<T> for CrossbeamBoundedQueue<T> {
    fn enqueue(&self, item: T) -> Result<(), T> {
        self.sender.send(item).map_err(|e| e.0)
    }
    
    fn try_enqueue(&self, item: T) -> Result<(), T> {
        self.sender.try_send(item).map_err(|e| match e {
            crossbeam::channel::TrySendError::Full(item) => item,
            crossbeam::channel::TrySendError::Disconnected(item) => item,
        })
    }
    
    fn dequeue(&self) -> Option<T> {
        self.receiver.recv().ok()
    }
    
    fn try_dequeue(&self) -> Option<T> {
        self.receiver.try_recv().ok()
    }
    
    fn dequeue_timeout(&self, timeout: Duration) -> Option<T> {
        self.receiver.recv_timeout(timeout).ok()
    }
    
    fn len(&self) -> usize {
        self.receiver.len()
    }
    
    fn is_empty(&self) -> bool {
        self.receiver.is_empty()
    }
}

// 安全trait实现
unsafe impl<T: Send> Send for CrossbeamUnboundedQueue<T> {}
unsafe impl<T: Send> Sync for CrossbeamUnboundedQueue<T> {}

unsafe impl<T: Send> Send for CrossbeamBoundedQueue<T> {}
unsafe impl<T: Send> Sync for CrossbeamBoundedQueue<T> {}

/// 队列类型别名，用于向后兼容
pub type LockFreeMPMCQueue<T> = CrossbeamUnboundedQueue<T>;
pub type BoundedMPMCQueue<T> = CrossbeamBoundedQueue<T>;

